package guoanmaker.operator.business.dao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import guoanmaker.operator.business.model.OperatorServerClass;
import guoanmaker.operator.business.model.PersonalUser;
import guoanmaker.operator.business.model.ProvideArea;
import guoanmaker.operator.business.model.ProvideCity;
import guoanmaker.operator.business.model.ProvideCommodity;
import guoanmaker.operator.business.model.ProvideOrderForm;
import guoanmaker.operator.business.model.ProviderBusiness;
import guoanmaker.operator.business.modelnobind.OderFormRo;
import guoanmaker.operator.business.modelnobind.OperatorBusinessRo;
import guoanmaker.operator.business.repository.OperatorServerClassRepository;
import guoanmaker.operator.business.repository.PersonalUserRepository;
import guoanmaker.operator.business.repository.ProvideAreaRepository;
import guoanmaker.operator.business.repository.ProvideCityRepository;
import guoanmaker.operator.business.repository.ProvideCommodityRepository;
import guoanmaker.operator.business.repository.ProvideOrderFormRepository;
import guoanmaker.operator.business.repository.ProviderBusinessRepository;
@Repository
public class OperatorBusinessInfoDao {

	@PersistenceContext
	EntityManager em;
	
	@Autowired
	private  ProviderBusinessRepository providerBusinessRepository;
	
	@Autowired
	private PersonalUserRepository  personalUserRepository;
	
	@Autowired
	private  ProvideCommodityRepository provideCommodityRepository;
	
	@Autowired
	private ProvideOrderFormRepository provideOrderFormRepository;
	

	@Autowired
	private ProvideAreaRepository  provideAreaRepository;
	
	@Autowired
	private OperatorServerClassRepository  operatorServerClassRepository;
	
	@Autowired
	private ProvideCityRepository  provideCityRepository;
	
	public Map<String,Object>  selectBusinessInfosPage(Integer page,Integer size){
		String jpql="select new guoanmaker.operator.business.modelnobind.OperatorBusinessRo(b.id,u.username,b.companyName,b.createDate,b.companyCity,b.companyArea,b.commoditys,"
				+ "u.isProvider) from ProviderBusiness b  left join  b.personalUser u ";
		if(page==null){
			page=0;
		}
		if (size==null) {
			size=10;
		}
		Query query1 = em.createQuery(jpql);
		List<OperatorBusinessRo> result1 =query1.getResultList();
		Map<String,Object>  map=new HashMap<>();
		map.put("totle", result1.size());
		query1.setFirstResult(page*size);
		query1.setMaxResults(size);
		List<OperatorBusinessRo> listI =query1.getResultList();
		map.put("result", listI);
		return  map;
	};
	
	public List<OperatorServerClass> selectById(String pids) {
		List<OperatorServerClass> lists = null;
		if (StringUtils.isNotEmpty(pids)) {
			if (!pids.equals("")) {
				String[] commoditySs = pids.split(",");
				@SuppressWarnings("rawtypes")
				List twoIdList = new ArrayList();
				Collections.addAll(twoIdList, commoditySs);
				lists = operatorServerClassRepository.findByIdIn(twoIdList);
			}
		}
		return lists;
	}
	
	
	public Map<String,Object>  selectBusinessServerinfosPage(Integer page,Integer size,Integer status){
		String jpql="select new guoanmaker.operator.business.modelnobind.ProviderBusiness(b.id,u.username,b.companyName,b.createDate,b.companyCity,b.companyArea,b.commoditys,"
				+ "u.isProvider) from ProviderBusiness b  left join  b.personalUser u where 1=1";
		jpql+="and u.isProvider=2 and b.serviceRange='"+status+"'";
		if(page==null){
			page=0;
		}
		if (size==null) {
			size=10;
		}
		Query query1 = em.createQuery(jpql);
		List<ProviderBusiness> result1 =query1.getResultList();
		Map<String,Object>  map=new HashMap<>();
		map.put("totle", result1.size());
		query1.setFirstResult(page*size);
		query1.setMaxResults(size);
		List<ProviderBusiness> listI =query1.getResultList();
		if(listI.size()>0){
			PersonalUser  personalUser=new PersonalUser();
			for (ProviderBusiness providerBusiness : listI) {
				// 业务类别
				String str = providerBusiness.getCommoditys();
				if(str!=null){
					String servername = "";
	    			List<OperatorServerClass> servers=	selectById(str);
	    			if(servers.size()>0&&servers!=null){
	    				for (OperatorServerClass operatorServerClass : servers) {
	    					servername += operatorServerClass.getServerName()+",";
	    				}
	    			}
	    			if(servers==null){
	    				 servername = "";
	    			}
					providerBusiness.setCommoditys(servername);
				}
				personalUser=providerBusiness.getPersonalUser();
				personalUser.setOrderforms(null);
			}
		}
		map.put("result", listI);
		return  map;
		
		
	}
	
	
	
	
	
	
	public List<OperatorBusinessRo>   selectBusinessInfos(){
		String jpql="select new guoanmaker.operator.business.modelnobind.OperatorBusinessRo(b.id,u.username,b.companyName,b.createDate,b.companyCity,b.companyArea,b.commoditys,"
				+ "u.isProvider) from ProviderBusiness b  left join  b.personalUser u ";
		Query query1 = em.createQuery(jpql);
		List<OperatorBusinessRo> listI =query1.getResultList();
		return  listI;
	};
	/**
	 * 
	 * @param page                        默认为0
	 * @param size                        每页10条
	 * @param acount                      商户账号
	 * @param status                      状态
	 * @param volume                      成交量
	 * @param volumesymbol                成交量符号          (大于，等于，小于)
	 * @param clinchadealAmount           成交金额
	 * @param clinchadealAmountsymbol     成交金额符号
	 * @param closing                     成交率
	 * @param closingsymbol               成交率符号
	 * @param serverclass                 服务种类
	 * @return
	 */
 /*  public Map<String, Object>  selectBusiness(Integer page,Integer size,String acount,String status,Integer volume, String volumesymbol, 
            Double clinchadealAmount,String clinchadealAmountsymbol,Double closing, String closingsymbol, String serverclass){
	   String jpql="";
	   OperatorBusinessRo  operatorBusinessRo=null;
	   List<OperatorBusinessRo>  lists=new ArrayList<>();
	   jpql="select new guoanmaker.operator.business.modelnobind.OperatorBusinessRo(b.id,u.username,b.companyName,b.createDate,b.companyCity,b.companyArea,b.commoditys,"
				+ "u.isProvider,b.busNumber) from ProviderBusiness b  left join  b.personalUser u where 1=1";
		   if(acount!=null&&!acount.equals("")){
				 jpql+="and u.username like '%'"+acount+"'%'";
			}else if(status!=null&&!status.equals("")&&status.equals("所有")){
				jpql+="and u.isProvider=4&&u.isProvider=2";
			} else if(status!=null&&!status.equals("")&&status.equals("正常")){
			     jpql+="and u.isProvider=2";
			}else if(status!=null&&!status.equals("")&&status.equals("冻结")){
				 jpql+="and u.isProvider=4";
			}else if(serverclass!=null&&!serverclass.equals("")){
				  jpql+="and b.commoditys LIKE '%"+serverclass+"%'";
			}
		   jpql+="and u.isProvider=4 or u.isProvider=2";
		    if(page==null){
					page=0;
				} 
				if (size==null) {
					size=10;
				}
				
				Query query = em.createQuery(jpql);
				List<OperatorBusinessRo> result = query.getResultList();
				Map<String,Object>  map=new HashMap<>();
				map.put("totle", result.size());
				query.setFirstResult(page*size);
				query.setMaxResults(size);
				List<OperatorBusinessRo> listI = query.getResultList();
				
			if(listI.size()>0){
				 for (int i = 0; i < listI.size(); i++) {
					   operatorBusinessRo=listI.get(i);
					//发布商品数量
						Integer num=provideCommodityRepository.selectCommidityNum(operatorBusinessRo.getId());
						operatorBusinessRo.setRelease(num);
						//地区
						ProvideArea provideArea=provideAreaRepository.findBycode(operatorBusinessRo.getCompanyArea());
						operatorBusinessRo.setCompanyArea(provideArea.getName());
						//城市
						ProvideCity provideCity	= provideCityRepository.findBycode(operatorBusinessRo.getCompanyCity());
						operatorBusinessRo.setCompanyCity(provideCity.getName());
						//交易金额
						List<ProvideCommodity>  prcs = provideCommodityRepository.selectByCommodity(operatorBusinessRo.getId());
						Double sumPrice=0.0;//交易金额
						int volume1=0;//成交量
						int sumvolume=0; //生成订单总数
						for (ProvideCommodity provideCommodity : prcs) {
						  Double shangpinPrice=0.0;	
						  int volumeuniq=0;
						  int vo=0;
						  List<ProvideOrderForm> pofs=  provideOrderFormRepository.selectBycommodity(provideCommodity.getId());
						  if(pofs.size()>0){
							  shangpinPrice=provideOrderFormRepository.selectSumrRate(provideCommodity.getId());
							  if(shangpinPrice==0.0){
								  shangpinPrice=0.0;
							  }
						  }
					      volumeuniq= provideOrderFormRepository.selectBycountvolume(provideCommodity.getId());
					       vo=provideOrderFormRepository.selectBycountTotalOrder(provideCommodity.getId());
					      sumvolume+=vo;  
					      sumPrice+=shangpinPrice;
					      volume1+=volumeuniq;
						}
						operatorBusinessRo.setTransactionAmount(sumPrice);
						//成交率(成交量/生成订单总数)   
						//成交量：成交笔数完成             成交是以最终客户确认，订单全部关闭为准  
						//生成订单总数：平台生成的订单量（订单总数）
						String str_i=Integer.toString(volume1);
						String str_j=Integer.toString(sumvolume);
						if(volume1==0||volume1==0&&sumvolume==0){
							operatorBusinessRo.setClosing(0.0);
						}else{
							operatorBusinessRo.setClosing(Double.valueOf(str_i)/Double.valueOf(str_j));
						}
						
						// 业务类别
						String str = operatorBusinessRo.getCommoditys();
						if(str!=null&&!str.equals("")){
							String[] strArr = str.split(",");
							String serverid = "";
							String servername = "";
							for (int j = 0; j < strArr.length; j++) {
								serverid = strArr[j];
								OperatorServerClass operatorServerClass = operatorServerClassRepository.findOne(serverid);
								servername += operatorServerClass.getServerName() + ",";
							}
							operatorBusinessRo.setCommoditys(servername);
						}
					  
				 }
				
			}
			map.put("result", listI);
		 if(volumesymbol!=null&&volumesymbol.equals("大于")&&volume!=null){
			      for (int i = 0; i < listI.size(); i++) {
			    	  operatorBusinessRo=listI.get(i);
			    	  if(operatorBusinessRo.getRelease()!=null){
			    		  if(volume<operatorBusinessRo.getRelease()){
			    			  if(lists.size()>0){
			    				  OperatorBusinessRo  operatorBusinessRo1=new OperatorBusinessRo();
			    				 for (int j = 0; j < lists.size(); j++) {
			    					  operatorBusinessRo1=lists.get(i);
			    					  if(volume<operatorBusinessRo1.getRelease()){
			    						  lists.add(operatorBusinessRo);
			    					  }else{
			    						  lists.remove(i);
			    					  }
								}
			    			  }else{
			    				  lists.add(operatorBusinessRo);
			    			  }
			    		  }
			    	  }
				   }
			  }else if(volumesymbol!=null&&volumesymbol.equals("小于")&&volume!=null){
				  for (int i = 0; i < listI.size(); i++) {
			    	  operatorBusinessRo=listI.get(i);
			    	  if(operatorBusinessRo.getRelease()!=null){
			    		  if(volume>operatorBusinessRo.getRelease()){
			    			  if(lists.size()>0){
			    				  OperatorBusinessRo  operatorBusinessRo1=new OperatorBusinessRo();
			    				 for (int j = 0; j < lists.size(); j++) {
			    					  operatorBusinessRo1=lists.get(i);
			    					  if(operatorBusinessRo1.getRelease()<volume){
			    						  lists.add(operatorBusinessRo);
			    					  }else{
			    						  lists.remove(i);
			    					  }
								}
			    			  }else{
			    				  lists.add(operatorBusinessRo);
			    			  }
			    		  }
			    	  }
				   }
			  }else if(volumesymbol!=null&&volumesymbol.equals("等于")&&volume!=null){
				  for (int i = 0; i < listI.size(); i++) {
			    	  operatorBusinessRo=listI.get(i);
			    	  if(operatorBusinessRo.getRelease()!=null){
			    		  if(volume==operatorBusinessRo.getRelease()){
			    			  if(lists.size()>0){
			    				  OperatorBusinessRo  operatorBusinessRo1=new OperatorBusinessRo();
			    				 for (int j = 0; j < lists.size(); j++) {
			    					  operatorBusinessRo1=lists.get(i);
			    					  if(operatorBusinessRo1.getRelease()==volume){
			    						  lists.add(operatorBusinessRo);
			    					  }else{
			    						  lists.remove(i);
			    					  }
								}
			    			  }else{
			    				  lists.add(operatorBusinessRo);
			    			  }
			    		  }
			    	  }
				   }
			   }else if(clinchadealAmountsymbol!=null&&clinchadealAmountsymbol.equals("大于")&&clinchadealAmount!=null){
				   for (int i = 0; i < listI.size(); i++) {
				    	  operatorBusinessRo=listI.get(i);
				    	  if(operatorBusinessRo.getTransactionAmount()!=null){
				    		  if(clinchadealAmount<operatorBusinessRo.getTransactionAmount()){
				    			  if(lists.size()>0){
				    				  OperatorBusinessRo  operatorBusinessRo1=new OperatorBusinessRo();
				    				 for (int j = 0; j < lists.size(); j++) {
				    					  operatorBusinessRo1=lists.get(i);
				    					  if(clinchadealAmount<operatorBusinessRo1.getTransactionAmount()){
				    						  lists.add(operatorBusinessRo);
				    					  }else{
				    						  lists.remove(i);
				    					  }
									}
				    			  }else{
				    				  lists.add(operatorBusinessRo);
				    			  }
				    		  }
				    	  }
					   }
			   } else if(clinchadealAmountsymbol!=null&&clinchadealAmountsymbol.equals("小于")&&clinchadealAmount!=null){
				   for (int i = 0; i < listI.size(); i++) {
				    	  operatorBusinessRo=listI.get(i);
				    	  if(operatorBusinessRo.getTransactionAmount()!=null){
				    		  if(clinchadealAmount>operatorBusinessRo.getTransactionAmount()){
				    			  if(lists.size()>0){
				    				  OperatorBusinessRo  operatorBusinessRo1=new OperatorBusinessRo();
				    				 for (int j = 0; j < lists.size(); j++) {
				    					  operatorBusinessRo1=lists.get(i);
				    					  if(clinchadealAmount>operatorBusinessRo1.getTransactionAmount()){
				    						  lists.add(operatorBusinessRo);
				    					  }else{
				    						  lists.remove(i);
				    					  }
									}
				    			  }else{
				    				  lists.add(operatorBusinessRo);
				    			  }
				    		  }
				    	  }
					   }
				   
			   }else if(clinchadealAmountsymbol!=null&&clinchadealAmountsymbol.equals("等于")&&clinchadealAmount!=null){
				   for (int i = 0; i < listI.size(); i++) {
				    	  operatorBusinessRo=listI.get(i);
				    	  if(operatorBusinessRo.getTransactionAmount()!=null){
				    		  if(clinchadealAmount==operatorBusinessRo.getTransactionAmount()){
				    			  if(lists.size()>0){
				    				  OperatorBusinessRo  operatorBusinessRo1=new OperatorBusinessRo();
				    				 for (int j = 0; j < lists.size(); j++) {
				    					  operatorBusinessRo1=lists.get(i);
				    					  if(clinchadealAmount==operatorBusinessRo1.getTransactionAmount()){
				    						  lists.add(operatorBusinessRo);
				    					  }else{
				    						  lists.remove(i);
				    					  }
									}
				    			  }else{
				    				  lists.add(operatorBusinessRo);
				    			  }
				    		  }
				    	  }
					   }
				   
			   }else if(closingsymbol!=null&&closingsymbol.equals("大于")&&closing!=null){
				   for (int i = 0; i < listI.size(); i++) {
				    	  operatorBusinessRo=listI.get(i);
				    	  if(operatorBusinessRo.getClosing()!=null){
				    		  if(closing<operatorBusinessRo.getClosing()){
				    			  if(lists.size()>0){
				    				  OperatorBusinessRo  operatorBusinessRo1=new OperatorBusinessRo();
				    				 for (int j = 0; j < lists.size(); j++) {
				    					  operatorBusinessRo1=lists.get(i);
				    					  if(closing<operatorBusinessRo1.getClosing()){
				    						  lists.add(operatorBusinessRo);
				    					  }else{
				    						  lists.remove(i);
				    					  }
									}
				    			  }else{
				    				  lists.add(operatorBusinessRo);
				    			  }
				    		  }
				    	  }
					   }
				   
			   }else if(closingsymbol!=null&&closingsymbol.equals("小于")&&closing!=null){
				   for (int i = 0; i < listI.size(); i++) {
				    	  operatorBusinessRo=listI.get(i);
				    	  if(operatorBusinessRo.getClosing()!=null){
				    		  if(closing>operatorBusinessRo.getClosing()){
				    			  if(lists.size()>0){
				    				  OperatorBusinessRo  operatorBusinessRo1=new OperatorBusinessRo();
				    				 for (int j = 0; j < lists.size(); j++) {
				    					  operatorBusinessRo1=lists.get(i);
				    					  if(closing>operatorBusinessRo1.getClosing()){
				    						  lists.add(operatorBusinessRo);
				    					  }else{
				    						  lists.remove(i);
				    					  }
									}
				    			  }else{
				    				  lists.add(operatorBusinessRo);
				    			  }
				    		  }
				    	  }
					   }
				   
			   }else if(closingsymbol!=null&&closingsymbol.equals("等于")&&closing!=null){
				   for (int i = 0; i < listI.size(); i++) {
				    	  operatorBusinessRo=listI.get(i);
				    	  if(operatorBusinessRo.getClosing()!=null){
				    		  if(closing==operatorBusinessRo.getClosing()){
				    			  if(lists.size()>0){
				    				  OperatorBusinessRo  operatorBusinessRo1=new OperatorBusinessRo();
				    				 for (int j = 0; j < lists.size(); j++) {
				    					  operatorBusinessRo1=lists.get(i);
				    					  if(closing==operatorBusinessRo1.getClosing()){
				    						  lists.add(operatorBusinessRo);
				    					  }else{
				    						  lists.remove(i);
				    					  }
									}
				    			  }else{
				    				  lists.add(operatorBusinessRo);
				    			  }
				    		  }
				    	  }
					   }
				 
			   }
		
		 return  map;
	};*/
	

	
	
	
	
	
}
